// ==UserScript==
// @name         51cto-m3u8-play
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://saas.51cto.com/learner.html
// @grant        none
// ==/UserScript==
function js_hook(_obj, _fn_name, _hook_call) {
    var _class = _obj;
    if (typeof _obj === "function") {
        _class = _obj.constructor;
    };
    var original = _class[_fn_name];
    _class[_fn_name] = function () {
        return _hook_call.call(this, original, arguments);
    };
};


function localStorage_pop(pre) {
    let item = Object.entries(localStorage).sort().find(v => v[0].substr(0, pre.length) == pre);
    if (item) {
        let key = item[0];
        let val = item[1];
        localStorage.removeItem(key);
        return val;
    }
    else {
        return null;
    }
}
function localStorage_push(pre, val) {

    let key = pre + new Date().valueOf() + '.' + Math.random();
    localStorage.setItem(key, val);
}

function setDivCenter(divName){  
    var top = ($(window).height() - $(divName).height())/2;  
    var left = ($(window).width() - $(divName).width())/2;  
    var scrollTop = $(document).scrollTop();  
    var scrollLeft = $(document).scrollLeft();  
    $(divName).css( {'background-color':'white', position : 'absolute', 'top' : top + scrollTop, 'left' : left + scrollLeft ,'z-index':10000} ).show(); 
} 

function saveToServer(param) {
    // let url = 'https://hw.p0q.top/cto/add?data=' + encodeURIComponent(JSON.stringify(param));
    // console.log(url)
    // new Image().src = url;
    //courseid=17945&lessonid=388057
    let matchs = /courseid=(\d+)&lessonid=(\d+)/.exec(location.href);
    if (!(matchs && matchs.length == 3)) {
        console.warn('找不到学科和课程标志');
        return;
    }

    param.courseid = matchs[1];
    param.lessonid = matchs[2];



    $.post('https://hw.p0q.top/cto/add', param, result => {
        console.log(result);

        if($('div#saved_cto').length == 0){
            $(document.body).append('<div id="saved_cto" style="width:600px;height:800px;"><ul></ul><a id="close_save_cto">关闭</a></div>');
            $('#close_save_cto').click((e)=>{
                $('div#saved_cto').hide();
            })
        }

        $('div#saved_cto ul').append("<li><a href='" + result.player + "'>" + result.title + ":" + result.player + "</a></li>");
        
        setDivCenter('div#saved_cto');
    })
}

(function () {
    'use strict'
    let saveParam = { title: "", m3u8: "", pwd: "", ok: false }

    /*js_hook((window.URL || window.webkitURL || window.mozURL || window.msURL),"createObjectURL",function (org,args) {
        console.debug("createObjectURL",args);
        //args[0] = "hook_"+args[0];
        return org.apply(this,args);
    });

    js_hook(window ,"Worker",function (org,args) {
        console.debug("Worker",args);
        return new org(args[0],args[1],args[2],args[3],args[4]);
    });*/
    js_hook(XMLHttpRequest.prototype, "open", function (org, args) {
        if (args[0] == "GET" && args[1].indexOf('m3u8') != -1) {
            console.log("m3u8", args[1]);
            saveParam.m3u8 = args[1];
            saveParam.ok = false;
            //localStorage.setItem(_lid + "_u3m8_url_",args[1]);
        }
        return org.apply(this, args);
    });


    function receiveMessage(e) {
        if (e.data && e.data.type == "getpwd") {
            if (saveParam.ok == false) {
                saveParam.ok = true;
                saveParam.token = localStorage.getItem('51CTO_ATHENA_TOKEN');
                saveParam.pwd = e.data.pwd;
                saveParam.title = document.title;

                saveToServer(saveParam);

                console.log("geted pwd", saveParam);
            }
        }
    }
    top.addEventListener("message", receiveMessage, false);

    js_hook(window, "Worker", function (org, args) {
        console.debug("Worker", args);
        var worker = new org(args[0], args[1], args[2], args[3], args[4]);
        worker.addEventListener("message", receiveMessage);
        /*setTimeout(function(){
            if(worker.onmessage){
console.log('found ed worker on message',work.onmessage);
            }
        },2000);*/
        return worker;
    });

    js_hook(window, "Blob", function (org, args) {
        console.debug("Blob", args);

        if (args.length >= 2 && args[1].type == "text/javascript") {
            args[0] = [args[0][0].replace(/u\.enc\.Utf8\.parse\(t\)/g, 'u.enc.Utf8.parse((postMessage({type:"getpwd", pwd:t}),t))')];
            console.debug("Blob, new arg:", args);
        }

        return new org(args[0], args[1]);
    });

    // Your code here...
})();